package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.I${entity}Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.List;

@RestController
@RequestMapping("/${entity?uncap_first}")
public class ${entity}Controller extends BaseController {

    @Autowired
    private I${entity}Service ${entity?uncap_first}Service;

    @PostMapping
    public ResponseEntity add(@RequestBody ${entity} ${entity?uncap_first}) {
        boolean saved = ${entity?uncap_first}Service.save(${entity?uncap_first});
        return saved ? success("创建成功", null) : error("创建失败");
    }

    @GetMapping("/{id}")
    public ResponseEntity getById(@PathVariable Long id) {
        ${entity} ${entity?uncap_first} = ${entity?uncap_first}Service.getById(id);
        return ${entity?uncap_first} != null ? success(${entity?uncap_first}) : error("未找到对应记录");
    }

    @PutMapping
    public ResponseEntity update(@RequestBody ${entity} ${entity?uncap_first}) {
        boolean updated = ${entity?uncap_first}Service.updateById(${entity?uncap_first});
        return updated ? success("更新成功", null) : error("更新失败");
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        boolean deleted = ${entity?uncap_first}Service.removeById(id);
        return deleted ? success("删除成功", null) : error("删除失败");
    }

    @GetMapping("/list")
    public ResponseEntity list() {
        List<${entity}> list = ${entity?uncap_first}Service.list();
        return success(list);
    }

    @GetMapping("/page")
    public ResponseEntity page(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              @ModelAttribute ${entity} ${entity?uncap_first}) {
        // 创建分页对象
        Page<${entity}> page = new Page<>(pageNum, pageSize);
        
        // 创建查询条件
        LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
        // 如果实体对象不为null，则根据实际情况添加查询条件
        if (${entity?uncap_first} != null) {
            <#list table.fields as field>
            // ${field.comment!}
            if (${entity?uncap_first}.get${field.propertyName?cap_first}() != null) {
                queryWrapper.eq(${entity}::get${field.propertyName?cap_first}, ${entity?uncap_first}.get${field.propertyName?cap_first}());
            }
            </#list>
        }
        
        // 执行分页查询
        page = ${entity?uncap_first}Service.page(page, queryWrapper);
        return success(page);
    }
}